﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Noris.Tools.TraceVisualiser.Apollo
{
    public class TraceSupport
    {
        public static string ShortSqlCommandText(string sqlCommand, int maxColumns, int maxRows)
        {
            if (String.IsNullOrEmpty(sqlCommand)) return "";
            int maxLen = maxColumns * maxRows;
            if (sqlCommand.Length > maxLen)
                sqlCommand = sqlCommand.Substring(0, maxLen) + "...";

            StringBuilder sb = new StringBuilder();
            char[] delimiters = new char[] { ' ', ',' };
            
            string[] lines = sqlCommand.Replace("\r\n", "\r").Replace("\n\r", "\r").Replace("\n", "\r").Split('\r');
            bool addEol = false;
            int cntRow = 0;
            foreach (string line in lines)
            {
                if (cntRow >= maxRows)
                {
                    sb.Append("  ...");
                    break;
                }
                string row = line.TrimEnd();
                if (row.Length <= maxColumns)
                {
                    if (addEol) sb.AppendLine(); else addEol = true;
                    sb.Append(row);
                    cntRow++;
                }
                else
                {
                    string prefix = "";
                    while (row.Length > 0)
                    {
                        if (cntRow >= maxRows)
                        {
                            sb.Append("  ...");
                            break;
                        }
                        int at = (row.Length > 100 ? row.IndexOfAny(delimiters, 100) : -1);
                        if (at > 0)
                        {
                            if (addEol) sb.AppendLine(); else addEol = true;
                            sb.Append(prefix + row.Substring(0, at + 1));
                            if (at == row.Length)
                                row = "";
                            else
                                row = row.Substring(at + 1).Trim();
                            prefix = "   ";
                            cntRow++;
                        }
                        else
                        {
                            if (addEol) sb.AppendLine(); else addEol = true;
                            sb.Append(prefix + row);
                            cntRow++;
                            row = "";
                        }
                    }
                }
            }

            return sb.ToString();
        }
    }
	/// <summary>
	/// Druh řádku: System-Begin-End
	/// </summary>
	public enum LineBSE
	{
		None = 0,
		System,
		Begin,
		End
	}
	/// <summary>
	/// Základní hodnoty z trace souboru (Info / Warning / Error)
	/// </summary>
	public enum LineIWE
	{
		None = 0,
		Information,
		Warning,
		Error
	}
}
